package com.study.lease.web.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.study.lease.common.constant.RedisConstant;
import com.study.lease.model.entity.*;
import com.study.lease.model.enums.ItemType;
import com.study.lease.web.admin.mapper.*;
import com.study.lease.web.admin.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.study.lease.web.admin.vo.attr.AttrValueVo;
import com.study.lease.web.admin.vo.graph.GraphVo;
import com.study.lease.web.admin.vo.room.RoomDetailVo;
import com.study.lease.web.admin.vo.room.RoomItemVo;
import com.study.lease.web.admin.vo.room.RoomQueryVo;
import com.study.lease.web.admin.vo.room.RoomSubmitVo;
import io.swagger.v3.oas.annotations.media.Schema;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liubo
 * @description 针对表【room_info(房间信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class RoomInfoServiceImpl extends ServiceImpl<RoomInfoMapper, RoomInfo>
        implements RoomInfoService {

    @Autowired
    private GraphInfoService graphInfoService;
    @Autowired
    private RoomAttrValueService roomAttrValueService;
    @Autowired
    private RoomFacilityService roomFacilityService;
    @Autowired
    private RoomLabelService roomLabelService;
    @Autowired
    private RoomLeaseTermService roomLeaseTermService;
    @Autowired
    private RoomPaymentTypeService roomPaymentTypeService;

    @Autowired
    private RoomInfoMapper roomInfoMapper;
    @Autowired
    private ApartmentInfoMapper apartmentInfoMapper;
    @Autowired
    private GraphInfoMapper graphInfoMapper;
    @Autowired
    private AttrValueMapper attrValueMapper;
    @Autowired
    private FacilityInfoMapper facilityInfoMapper;
    @Autowired
    private LabelInfoMapper labelInfoMapper;
    @Autowired
    private PaymentTypeMapper paymentTypeMapper;
    @Autowired
    private LeaseTermMapper leaseTermMapper;

    @Autowired
    private RedisTemplate<String,Object>  redisTemplate;

    @Override
    public void saveOrUpdateRoom(RoomSubmitVo roomSubmitVo) {
        /**
         * 该super.saveOrUpdate()方法，会根据主键id判断是保存还是更新，
         */
        boolean isUpdate = roomSubmitVo.getId() != null;
        /**
         * //保存或更新房间信息，是RoomSubmitVo继承的RoomInfo的信息
         * 后面再分别单独保存其他信息
         */
        super.saveOrUpdate(roomSubmitVo);
        //若为更新，则删除该房间的图片、属性、标签、配套、支付方式、租赁期
        if (isUpdate){
            //删除该房间的图片、属性、标签、配套、支付方式、租赁
            //1.删除图片信息
            LambdaQueryWrapper<GraphInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(GraphInfo::getItemType, ItemType.ROOM);
            queryWrapper.eq(GraphInfo::getItemId,roomSubmitVo.getId()); //getId()为roomSubmitVo的id
            graphInfoService.remove(queryWrapper);
            //2.删除属性列表
            LambdaQueryWrapper<RoomAttrValue> roomqueryWrapper = new LambdaQueryWrapper<>();
            roomqueryWrapper.eq(RoomAttrValue::getRoomId,roomSubmitVo.getId());
            roomAttrValueService.remove(roomqueryWrapper);
            //3.删除配套列表
            LambdaQueryWrapper<RoomFacility> facilityQueryWrapper = new LambdaQueryWrapper<>();
            facilityQueryWrapper.eq(RoomFacility::getRoomId,roomSubmitVo.getId());
            roomFacilityService.remove(facilityQueryWrapper);
            //4.删除标签列表
            LambdaQueryWrapper<RoomLabel> labelQueryWrapper = new LambdaQueryWrapper<>();
            labelQueryWrapper.eq(RoomLabel::getRoomId,roomSubmitVo.getId());
            roomLabelService.remove(labelQueryWrapper);
            //5.删除租赁期列表
            LambdaQueryWrapper<RoomLeaseTerm> leaseTermQueryWrapper = new LambdaQueryWrapper<>();
            leaseTermQueryWrapper.eq(RoomLeaseTerm::getRoomId,roomSubmitVo.getId());
            roomLeaseTermService.remove(leaseTermQueryWrapper);
            //6.删出支付方式列表
            LambdaQueryWrapper<RoomPaymentType> paymentTermQueryWrapper = new LambdaQueryWrapper<>();
            paymentTermQueryWrapper.eq(RoomPaymentType::getRoomId,roomSubmitVo.getId());
            roomPaymentTypeService.remove(paymentTermQueryWrapper);

            //删除缓存
            String key = RedisConstant.APP_ROOM_PREFIX +roomSubmitVo.getId();
            redisTemplate.delete(key);

        }

        //1. 插入图片信息
        List<GraphVo> graphVoList = roomSubmitVo.getGraphVoList();
        if(!CollectionUtils.isEmpty(graphVoList)){
            ArrayList<GraphInfo> graphInfoArrayList = new ArrayList<>();
            for (GraphVo graphVo: graphVoList){
                /**
                 * 为什么使用graphInfo.set(),而不是get()方法？
                 * 因为set()方法在这里的意义是设置属性值，而不是获取属性值
                 */
                GraphInfo graphInfo = new GraphInfo();
                graphInfo.setItemType(ItemType.ROOM);
                graphInfo.setItemId(roomSubmitVo.getId());//插入图片所属对象id
                graphInfo.setName(graphVo.getName());
                graphInfo.setUrl(graphVo.getUrl());
                graphInfoArrayList.add(graphInfo);
            }
            graphInfoService.saveBatch(graphInfoArrayList);//批量插入图片信息
        }
        //2. 插入属性列表
        List<Long> attrValueIds = roomSubmitVo.getAttrValueIds();
        if (!CollectionUtils.isEmpty(attrValueIds)) {
            ArrayList<RoomAttrValue> roomAttrValueArrayList = new ArrayList<>();
            for(Long attrValueId: attrValueIds){
                RoomAttrValue roomAttrValue = new RoomAttrValue();
                roomAttrValue.setRoomId(roomSubmitVo.getId());
                roomAttrValue.setAttrValueId(attrValueId);
                roomAttrValueArrayList.add(roomAttrValue);

            }
            roomAttrValueService.saveBatch(roomAttrValueArrayList);
        }
        //3. 插入配套列表
        List<Long> facilityInfoIds = roomSubmitVo.getFacilityInfoIds();
        if (!CollectionUtils.isEmpty(facilityInfoIds)) {
            ArrayList<RoomFacility> roomFacilityArrayList = new ArrayList<>();
            for (Long facilityInfoId : facilityInfoIds) {
                RoomFacility roomFacility = new RoomFacility();
                roomFacility.setRoomId(roomSubmitVo.getId());
                roomFacility.setFacilityInfoId(facilityInfoId);
                roomFacilityArrayList.add(roomFacility);
            }
            roomFacilityService.saveBatch(roomFacilityArrayList);
        }
        //4. 插入标签列表
        List<Long> labelInfoIds = roomSubmitVo.getLabelInfoIds();
        if (!CollectionUtils.isEmpty(labelInfoIds)) {
            ArrayList<RoomLabel> roomLabelArrayList = new ArrayList<>();
            for (Long labelInfoId :labelInfoIds){
                RoomLabel roomLabel = new RoomLabel();
                roomLabel.setLabelId(labelInfoId);
                roomLabel.setRoomId(roomSubmitVo.getId());
                roomLabelArrayList.add(roomLabel);
            }
            roomLabelService.saveBatch(roomLabelArrayList);
        }
        //5. 插入租赁期列表
        List<Long> leaseTermIds = roomSubmitVo.getLeaseTermIds();
        if (!CollectionUtils.isEmpty(leaseTermIds)) {
            ArrayList<RoomLeaseTerm> roomLeaseTermArrayList = new ArrayList<>();
            for (Long leaseTermId : leaseTermIds) {
                RoomLeaseTerm roomLeaseTerm = new RoomLeaseTerm();
                roomLeaseTerm.setRoomId(roomSubmitVo.getId());
                roomLeaseTerm.setLeaseTermId(leaseTermId);
            }
            roomLeaseTermService.saveBatch(roomLeaseTermArrayList);
        }
        //6. 插入支付方式列表
        List<Long> paymentTypeIds = roomSubmitVo.getPaymentTypeIds();
        if (!CollectionUtils.isEmpty(paymentTypeIds)) {
            ArrayList<RoomPaymentType> roomPaymentTypeArrayList = new ArrayList<>();
            for (Long paymentTypeId : paymentTypeIds) {
                RoomPaymentType roomPaymentType = new RoomPaymentType();
                roomPaymentType.setRoomId(roomSubmitVo.getId());
                roomPaymentType.setPaymentTypeId(paymentTypeId);
                roomPaymentTypeArrayList.add(roomPaymentType);
            }
            roomPaymentTypeService.saveBatch(roomPaymentTypeArrayList);
        }

    }

    /**
     * 根据条件分页查询房间列表
     * @param page
     * @param queryVo
     * @return
     */

    @Override
    public IPage<RoomItemVo> pageRoomItemByQuery(Page<RoomItemVo> page, RoomQueryVo queryVo) {

        return roomInfoMapper.pageRoomItemByQuery(page,queryVo);
    }

    /**
     * 根据id获取房间详情
     * @param id
     * @return
     */
    @Override
    public RoomDetailVo selcteDetailById(Long id) {
   /*     @Schema(description = "所属公寓信息")
        @Schema(description = "图片列表")
        @Schema(description = "属性信息列表")
        @Schema(description = "配套信息列表")
        @Schema(description = "标签信息列表")
        @Schema(description = "支付方式列表")
        @Schema(description = "可选租期列表")*/
        //1.查询房间信息
        RoomInfo roomInfo = roomInfoMapper.selectById(id);
        //2.查询所属公寓信息
        ApartmentInfo apartmentInfo = apartmentInfoMapper.selectById(roomInfo.getApartmentId());
        //3.查询图片列表
        List<GraphVo> graphVoList = graphInfoMapper.selectListByItemTypeAndId(ItemType.ROOM, id);
        //4.查询属性信息列表
        List<AttrValueVo> attrValueVoList = attrValueMapper.selectListByRoomId(id);
        //5.查询配套信息列表
        List<FacilityInfo> facilityInfoList = facilityInfoMapper.selectListByRoomId(id);
        //6.查询标签信息列表
        List<LabelInfo> labelInfoList = labelInfoMapper.selectListByRoomId(id);
        //7.查询支付方式列表
        List<PaymentType> paymentTypeList = paymentTypeMapper.selectListByRoomId(id);
        //8.查询可选租期列表
        List<LeaseTerm> leaseTermList = leaseTermMapper.selectListByRoomId(id);

        //9.组装结果
        RoomDetailVo roomDetailVo = new RoomDetailVo();
        BeanUtils.copyProperties(roomInfo,roomDetailVo);
        roomDetailVo.setApartmentInfo(apartmentInfo);
        roomDetailVo.setGraphVoList(graphVoList);
        roomDetailVo.setAttrValueVoList(attrValueVoList);
        roomDetailVo.setFacilityInfoList(facilityInfoList);
        roomDetailVo.setLabelInfoList(labelInfoList);
        roomDetailVo.setPaymentTypeList(paymentTypeList);
        roomDetailVo.setLeaseTermList(leaseTermList);
        return roomDetailVo;

    }

    /**
     * 根据id删除房间信息
     * @param id
     */
    @Override
    public void removeRoomById(Long id) {
        //8.删除房间信息
        super.removeById(id); //该super 是继承的ServiceImpl
        //1.删除图片信息
        LambdaQueryWrapper<GraphInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GraphInfo::getItemType, ItemType.ROOM);
        queryWrapper.eq(GraphInfo::getItemId,id); //getId()为roomSubmitVo的id
        graphInfoService.remove(queryWrapper);
        //2.删除属性列表
        LambdaQueryWrapper<RoomAttrValue> roomqueryWrapper = new LambdaQueryWrapper<>();
        roomqueryWrapper.eq(RoomAttrValue::getRoomId,id);
        roomAttrValueService.remove(roomqueryWrapper);
        //3.删除配套列表
        LambdaQueryWrapper<RoomFacility> facilityQueryWrapper = new LambdaQueryWrapper<>();
        facilityQueryWrapper.eq(RoomFacility::getRoomId,id);
        roomFacilityService.remove(facilityQueryWrapper);
        //4.删除标签列表
        LambdaQueryWrapper<RoomLabel> labelQueryWrapper = new LambdaQueryWrapper<>();
        labelQueryWrapper.eq(RoomLabel::getRoomId,id);
        roomLabelService.remove(labelQueryWrapper);
        //5.删除租赁期列表
        LambdaQueryWrapper<RoomLeaseTerm> leaseTermQueryWrapper = new LambdaQueryWrapper<>();
        leaseTermQueryWrapper.eq(RoomLeaseTerm::getRoomId,id);
        roomLeaseTermService.remove(leaseTermQueryWrapper);
        //6.删出支付方式列表
        LambdaQueryWrapper<RoomPaymentType> paymentTermQueryWrapper = new LambdaQueryWrapper<>();
        paymentTermQueryWrapper.eq(RoomPaymentType::getRoomId,id);
        roomPaymentTypeService.remove(paymentTermQueryWrapper);

        //删除缓存
        String key = RedisConstant.APP_ROOM_PREFIX+ id;
        redisTemplate.delete(key);

    }
}




